<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="账号名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入账号名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="职位" prop="maintainCompanyRole">
        <el-select
          v-model="queryParams.maintainCompanyRole"
          filterable
          placeholder="维保公司"
          clearable
        >
          <el-option
            v-for="(item, index) in ruleList"
            :key="index"
            :label="item.roleName"
            :value="item.roleId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="维保公司" prop="maintainCompanyId">
        <el-select
          v-model="queryParams.maintainCompanyId"
          filterable
          placeholder="维保公司"
          clearable
        >
          <el-option
            v-for="(item, index) in maintainCompanyList"
            :key="index"
            :label="item.companyName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wb:wbContract:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wb:wbContract:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wb:wbContract:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="wbContractList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账号名称" align="center" prop="userName" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="手机号" align="center" prop="phonenumber" />
      <el-table-column label="职位" align="center">
        <template slot-scope="{ row }">
          {{ row.wbRoles.map((ele) => ele.roleName).join(",") }}
        </template>
      </el-table-column>
      <el-table-column label="公司名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.companyName }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDetails(scope.row)"
            >查看</el-button
          >

          <el-button
            v-show="isShow == 'true'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wb:wbContract:edit']"
            >修改</el-button
          >
          <!-- <el-button
            v-show="isShow == 'true'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wb:wbContract:remove']"
            >删除</el-button
          > -->
          <el-button
            v-show="isShow == 'true'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleReset(scope.row)"
            v-hasPermi="['wb:wbContract:reset']"
            >重置账号</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维保合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :disabled="isDetails"
        label-width="110px"
        :inline="true"
        class="dialog-form"
        :key="formKey"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="isAdd" label="账号名称" prop="userName">
              <el-input
                v-model="form.userName"
                placeholder="请输入账号名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isAdd" label="用户密码" prop="password">
              <el-input
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!isReset">
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input
                v-model="form.nickName"
                placeholder="请输入昵称"
                style="width: 220px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input
                v-model="form.phonenumber"
                maxlength="11"
                placeholder="请输入手机号"
                style="width: 220px"
              />
            </el-form-item>
          </el-col>
          <el-form-item label="职位" prop="wbRoles" class="form-item-row">
            <el-select
              :disabled="form.disable"
              v-model="form.wbRoles"
              multiple
              filterable
              placeholder="请选择职位"
              style="width: 500px"
            >
              <el-option
                v-for="(item, index) in ruleList"
                :key="index"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="维保公司" prop="maintainCompanyId">
            <el-select
              v-model="form.maintainCompanyId"
              filterable
              placeholder="维保公司"
            >
              <el-option
                v-for="(item, index) in maintainCompanyList"
                :key="index"
                :label="item.companyName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item label="电子签名">
          <ImageUpload v-model="form.signature" :limit="1"></ImageUpload>
        </el-form-item>

        <el-form-item label="电子印章">
          <ImageUpload v-model="form.personalSeal" :limit="1"></ImageUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="isLoading" v-if="isLoading"
          >提交中...</el-button
        >
        <el-button
          type="primary"
          :disabled="isDetails"
          @click="submitForm"
          v-else
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWbUserList,
  addWbUser,
  queryWbUser,
  editWbUser,
  delWbContract,
  resetAccount,
} from "@/api/wb/userManage";
import { fomatterLabelName } from "@/utils/index.js";
import Dictionary from "@/utils/dictionary";
import { mapGetters, mapActions } from "vuex";
export default {
  name: "WbContract",
  data() {
    return {
      Dictionary,
      isDetails: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维保合同表格数据
      wbContractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        roleId: null,
        maintainCompanyId: null,
        userName: null,
      },
      // 默认密码
      initPassword: null,
      // 表单参数
      form: {
        signature: "",
        personalSeal: "",
      },
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        phonenumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
        ],
        maintainCompanyId: [
          { required: true, message: "公司不能为空", trigger: "blur" },
        ],
        wbRoles: [{ required: true, message: "职务不能为空", trigger: "blur" }],
      },
      ruleList: [],
      isAdd: true,
      isReset: false,
      formKey: true,
      isLoading: false,
      isShow: false,
    };
  },
  computed: {
    ...mapGetters(["maintainCompanyList"]),
  },
  async created() {
    // 查询所有维保公司
    this.ruleList = await this.getWbRoleList("");
    this.isShow = window.localStorage.getItem("isShow");

    this.getWbList();
    this.getList();
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    ...mapActions("reqSelect", ["getWbList"]),
    fomatterLabelName,
    /** 查询维保合同列表 */
    getList() {
      this.loading = true;
      listWbUserList(this.queryParams).then((response) => {
        this.wbContractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        wbRoles: [],
        maintainCompanyId: null,
        nickName: null,
        phonenumber: null,
        userName: null,
        password: null,
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    async handleDetails(row) {
      this.reset();
      const id = row.id;
      this.ruleList = await this.getWbRoleList("");

      queryWbUser(id).then((response) => {
        this.form = response.data;
        let wbRoles = response.data.wbRoles || [];
        response.data.wbRoles.forEach((item) => {
          if (item.roleId == 104) {
            this.ruleList.push({
              roleId: 104,
              roleName: "维保公司管理员",
            });
          }
        });

        this.form.wbRoles = wbRoles.map((ele) => ele.roleId);

        this.form.disable = false;

        this.ruleList.forEach((element) => {
          if (element.roleId == 104) {
            this.form.disable = true;
          }
        });

        this.open = true;
        this.title = "查看用户";
        this.form.password = "";
        this.form.userName = "";
        this.isAdd = false;
        this.isReset = false;
        this.isDetails = true;
      });
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.ruleList = await this.getWbRoleList("");
      this.isDetails = false;

      this.open = true;
      this.title = "添加用户";
      this.form.password = this.initPassword;
      this.isAdd = true;
      this.isReset = false;
      this.$set(this.rules, "userName", [
        { required: true, message: "用户名称不能为空", trigger: "blur" },
        {
          min: 2,
          max: 20,
          message: "用户名称长度必须介于 2 和 20 之间",
          trigger: "blur",
        },
      ]);
      this.$set(this.rules, "password", [
        { required: true, message: "用户密码不能为空", trigger: "blur" },
        {
          min: 5,
          max: 20,
          message: "用户密码长度必须介于 5 和 20 之间",
          trigger: "blur",
        },
        {
          pattern: /^[^<>"'|\\]+$/,
          message: "不能包含非法字符：< > \" ' \\\ |",
          trigger: "blur",
        },
      ]);
      this.formKey = !this.formKey;
      if (this.maintainCompanyList.length) {
        this.form.maintainCompanyId = this.maintainCompanyList[0].id;
      }
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id;
      this.ruleList = await this.getWbRoleList("");
      this.isDetails = false;

      queryWbUser(id).then((response) => {
        this.form = response.data;
        let wbRoles = response.data.wbRoles || [];
        response.data.wbRoles.forEach((item) => {
          if (item.roleId == 104) {
            this.ruleList.push({
              roleId: 104,
              roleName: "维保公司管理员",
            });
          }
        });

        this.form.wbRoles = wbRoles.map((ele) => ele.roleId);

        this.form.disable = false;

        this.ruleList.forEach((element) => {
          if (element.roleId == 104) {
            this.form.disable = true;
          }
        });

        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
        this.form.userName = "";
        this.isAdd = false;
        this.isReset = false;
      });
    },
    // 重置账号
    handleReset(row) {
      this.reset();
      this.open = true;
      this.title = "重置账号";
      this.form.password = "";
      this.isAdd = true;
      this.isReset = true;
      this.form.userName = row.userName;
      this.form.userId = row.id;
      this.form.maintainCompanyId = row.maintainCompanyId;
      this.$set(this.rules, "userName", [
        { required: true, message: "用户名称不能为空", trigger: "blur" },
        {
          min: 2,
          max: 20,
          message: "用户名称长度必须介于 2 和 20 之间",
          trigger: "blur",
        },
      ]);
      this.$set(this.rules, "password", [
        { required: true, message: "用户密码不能为空", trigger: "blur" },
        {
          min: 5,
          max: 20,
          message: "用户密码长度必须介于 5 和 20 之间",
          trigger: "blur",
        },
        {
          pattern: /^[^<>"'|\\]+$/,
          message: "不能包含非法字符：< > \" ' \\\ |",
          trigger: "blur",
        },
      ]);
      this.rules.userName = undefined;
      this.rules.password = undefined;
    },
    getRoleName(role) {
      if (!role || role == "" || role.length <= 0) return "";
      return role.map((ele) => this.ruleList).join(",");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.isLoading = true;

          let wbRoles = this.form.wbRoles.map((ele) => {
            let roleName =
              this.ruleList.find((item) => item.roleId == ele).roleName || "";
            return {
              roleId: ele,
              roleName,
            };
          });
          // if (this.isReset) {
          //   resetAccount(this.form).then(response => {
          //     this.$modal.msgSuccess("重置成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else
          if (this.form.userId) {
            editWbUser({ ...this.form, wbRoles }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.isLoading = false;
            });
          } else {
            addWbUser({ ...this.form, wbRoles }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.isLoading = false;
            });
          }
          this.isLoading = false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除维保合同编号为"' + ids + '"的数据项？')
        .then(function () {
          return delWbContract(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "wb/wbContract/export",
        {
          ...this.queryParams,
        },
        `wbContract_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
